<!-- Created by henian.xu on 2018/8/3. -->

<template>
    <el-cascader
        filterable
        class="router-picker"
        :props="props"
        :options="options"
        v-model="model"
    />
</template>

<script>
export default {
    name: 'RouterPicker',
    data() {
        return {
            props: {
                value: 'path',
                label: 'title',
                children: 'children',
                disabled: 'disabled',
            },
        };
    },
    props: {
        value: {
            type: String,
            required: true,
        },
    },
    computed: {
        model: {
            get() {
                if (!this.value) return [];
                const val = this.value.replace(/(^\/*)|(\/*$)/g, '');
                return val.split('/');
            },
            set(val) {
                this.$emit('input', '/' + val.join('/'));
            },
        },
        options() {
            return this.buildRouterOptions(this.$router.options.routes);
        },
    },
    methods: {
        buildRouterOptions(list, res = []) {
            const temMap = {};
            list.forEach(item => {
                const { name, meta } = item;
                const title = meta ? meta.title : '';
                if (name) {
                    const arr = name.split('-');
                    const arrLng = arr.length;
                    let temObj = res;
                    arr.forEach((item, index) => {
                        const isLast = index === arrLng - 1;
                        const key = [...arr].splice(0, index + 1).join('-');
                        let obj = temMap[key];
                        if (!obj) {
                            obj = temMap[key] = {
                                // title: isLast ? title : item,
                                title: item + (isLast ? ` (${title})` : ''),
                                path: item,
                            };
                            temObj.push(obj);
                        }
                        if (!isLast) {
                            temObj = obj.children = obj.children || [];
                        }
                    });
                }
                if (item.children && item.children.length) {
                    this.buildRouterOptions(item.children, res);
                }
            });
            return res;
        },
    },
};
</script>

<style lang="scss">
</style>
